/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package InterviewerManagerment.gui;

import Application.MarvellFrame;
import DataServices.Validate;
import InterviewerManagerment.entities.Interview;
import InterviewerManagerment.jdbc.Interviews;
import connection.Configuration;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Tngoc
 */
public class InterviewerGui extends javax.swing.JFrame implements MarvellFrame {

    private int id;
    private String staffName;
    private Interviews interviews;
    private DefaultTableModel model;
    private Validate validate;

    public int getId() {
        return id;
    }

    public void setId(int id, String staffName) {
        this.id = id;
        this.staffName = staffName;
        userInit();
    }

    private void userInit() {
        btnRequest.setEnabled(false);
        interviews = new Interviews(id);
        model = (DefaultTableModel) interviewTable.getModel();
        lblName.setText("hello " + staffName);
        setModelData();
        lblError.setVisible(false);
        lblErrorSalary.setVisible(false);
        this.validate = new Validate();
    }

    private void setModelData() {
        interviews.refresh();
        for (int i = model.getRowCount() - 1; i >= 0; i--) {
            model.removeRow(i);
        }
//        System.out.println(model.getRowCount());
        for (Interview i : interviews.getInterviews()) {
//          String rs, rq;
//            if(i.isResult()==){
//                rs = "pass";
//            }else{
//                rs="fail";
//            }
//            if(){
//                
//            }
            Object[] data = {i.getID(), i.getVacancyID(), i.getAmount(), i.getField(), i.getDate(), i.getSalary(), i.getSeekerID(), i.getSeekerName(), i.isResult(), i.isChangeRequest()};
            model.addRow(data);
        }
    }

    /**
     * Creates new form InterviewerGui
     */
    public InterviewerGui() {
        initComponents();
        userInit();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDialog1 = new javax.swing.JDialog();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        jPasswordField2 = new javax.swing.JPasswordField();
        btnChangePassSave = new javax.swing.JButton();
        btnChangePassCancel = new javax.swing.JButton();
        lblError = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        interviewTable = new javax.swing.JTable();
        btnRequest = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        btnResult = new javax.swing.JButton();
        btnBack = new javax.swing.JButton();
        btnChangePass = new javax.swing.JButton();
        lblName = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtSalary = new javax.swing.JTextField();
        lblErrorSalary = new javax.swing.JLabel();

        jLabel3.setText("password");

        jLabel4.setText("retype");

        btnChangePassSave.setText("save");
        btnChangePassSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChangePassSaveActionPerformed(evt);
            }
        });

        btnChangePassCancel.setText("cancel");
        btnChangePassCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChangePassCancelActionPerformed(evt);
            }
        });

        lblError.setForeground(new java.awt.Color(255, 0, 0));
        lblError.setText("retype");

        javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
        jDialog1.getContentPane().setLayout(jDialog1Layout);
        jDialog1Layout.setHorizontalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDialog1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jDialog1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jDialog1Layout.createSequentialGroup()
                                .addComponent(btnChangePassSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnChangePassCancel)
                                .addGap(0, 70, Short.MAX_VALUE))
                            .addGroup(jDialog1Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(lblError))))
                    .addGroup(jDialog1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPasswordField1)
                            .addComponent(jPasswordField2))
                        .addGap(50, 50, 50)))
                .addContainerGap())
        );
        jDialog1Layout.setVerticalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDialog1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblError))
                .addGap(26, 26, 26)
                .addGroup(jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnChangePassCancel)
                    .addComponent(btnChangePassSave))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

        interviewTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "VacancyID", "Amount", "Field", "Date", "salary", "seekerID", "seeker name", "result", "change request"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Float.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        interviewTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        interviewTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                interviewTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(interviewTable);

        btnRequest.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/alert-square-red.png"))); // NOI18N
        btnRequest.setText("request");
        btnRequest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRequestActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "waitting", "pass", "fail" }));
        jComboBox1.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                jComboBox1PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        btnResult.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/pencil.png"))); // NOI18N
        btnResult.setText("update");
        btnResult.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResultActionPerformed(evt);
            }
        });

        btnBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/Import Document.png"))); // NOI18N
        btnBack.setText("back");
        btnBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBackActionPerformed(evt);
            }
        });

        btnChangePass.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/Briefcase.png"))); // NOI18N
        btnChangePass.setText("change password");
        btnChangePass.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChangePassActionPerformed(evt);
            }
        });

        lblName.setFont(new java.awt.Font("Verdana", 3, 18)); // NOI18N
        lblName.setText("hello");

        jLabel2.setText("result");

        jLabel1.setText("salary");

        txtSalary.setEditable(false);

        lblErrorSalary.setForeground(new java.awt.Color(255, 0, 0));
        lblErrorSalary.setText("input salary");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1031, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblName, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnChangePass)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnBack)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(lblErrorSalary)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(txtSalary, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnResult, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnRequest)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblName, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(lblErrorSalary)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnChangePass)
                        .addComponent(btnBack))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtSalary, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel1))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2)))
                        .addComponent(btnResult, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnRequest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRequestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRequestActionPerformed

        if (interviewTable.getSelectedRow() != -1) {
            int flag;
            if ("false".equals(interviewTable.getValueAt(interviewTable.getSelectedRow(), 9).toString())) {
                flag = 1;
                model.setValueAt("true", interviewTable.getSelectedRow(), 9);
            } else {
                flag = 0;
                model.setValueAt("false", interviewTable.getSelectedRow(), 9);
            }
            int id1 = Integer.parseInt(interviewTable.getValueAt(interviewTable.getSelectedRow(), 0).toString());
            try {
                try (Connection conn = new Configuration().getConnect()) {
                    Statement st = conn.createStatement();
//                    System.out.println(id1);
                    st.executeUpdate("update Interview set changeRequest = " + flag + "where ID=" + id1);
                }
            } catch (SQLException ex) {
                Logger.getLogger(InterviewerGui.class.getName()).log(Level.SEVERE, null, ex);
            }
            setModelData();
        }
    }//GEN-LAST:event_btnRequestActionPerformed

    private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
        // TODO add your handling code here:
        exitFrame();
    }//GEN-LAST:event_btnBackActionPerformed

    private void btnResultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResultActionPerformed
        try {
            int select = interviewTable.getSelectedRow();
            int id1 = Integer.parseInt(interviewTable.getValueAt(select, 0).toString());
            String current = interviewTable.getValueAt(select, 8).toString();
            try (Connection conn = new Configuration().getConnect()) {
                Statement st = conn.createStatement();
                if ("pass".equals(jComboBox1.getSelectedItem().toString())) {
                    if ("".equals(txtSalary.getText()) || !validate.isNumber(txtSalary.getText())) {
                        lblErrorSalary.setVisible(true);
                    } else {
                        String salary = validate.change(txtSalary.getText());
                        String qry = "update interview set salary =" + salary + " where ID =" + id1;
                        System.out.println("qry: " + qry);
                        st.executeUpdate(qry);
                        lblErrorSalary.setVisible(false);
                    }
                    if(!"pass".equals(current)){
                        st.executeUpdate("update Vacancy set amount = amount-1 where ID = (select VacancyID from Interview where ID = "+id1+")");
                    }
                }else{
                    if("pass".equals(current)){
                        st.executeUpdate("update Vacancy set amount = amount+1 where ID = (select VacancyID from Interview where ID = "+id1+")");
                    }
                }
                CallableStatement cst = conn.prepareCall("{call submit(?," + id1 + ")}");
                switch (jComboBox1.getSelectedItem().toString()) {
                    case "waitting":
                        cst.setNull(1, java.sql.Types.BIT);
                        break;
                    case "fail":
                        cst.setBoolean(1, false);
                        break;
                    case "pass":
                        cst.setBoolean(1, true);
                        break;
                }
                //            System.out.println(id1);
                cst.executeUpdate();
            }
        setModelData();
        } catch (SQLException ex) {
            Logger.getLogger(InterviewerGui.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnResultActionPerformed

    private void jComboBox1PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jComboBox1PopupMenuWillBecomeInvisible
        if ("pass".equals(jComboBox1.getSelectedItem().toString())) {
            txtSalary.setEditable(true);
        } else {
            txtSalary.setEditable(false);
        }
    }//GEN-LAST:event_jComboBox1PopupMenuWillBecomeInvisible

    private void btnChangePassSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChangePassSaveActionPerformed
        String pass1 = String.valueOf(jPasswordField1.getPassword());
        String pass2 = String.valueOf(jPasswordField2.getPassword());
        if (pass1.equals(pass2)) {
            try {
                String qry = "update Staff set password = '" + pass1 + "' where ID = " + id;
                Statement st = new Configuration().getConnect().createStatement();
                st.executeUpdate(qry);
                st.getConnection().close();
                lblError.setVisible(false);
            } catch (SQLException ex) {
                Logger.getLogger(InterviewerGui.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            lblError.setVisible(true);
        }
        btnChangePassCancel.doClick();
    }//GEN-LAST:event_btnChangePassSaveActionPerformed

    private void btnChangePassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChangePassActionPerformed
        this.setEnabled(false);
        jDialog1.pack();
        jDialog1.setVisible(true);
        jPasswordField1.setText("");
        jPasswordField2.setText("");
    }//GEN-LAST:event_btnChangePassActionPerformed

    private void btnChangePassCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChangePassCancelActionPerformed
        this.setEnabled(true);
        jDialog1.setVisible(false);
    }//GEN-LAST:event_btnChangePassCancelActionPerformed

    private void interviewTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_interviewTableMouseClicked
        int select = interviewTable.getSelectedRow();
        if(select!=-1){
            if("waitting".equals(model.getValueAt(select, 8).toString())){
                btnRequest.setEnabled(true);
            }else{
                 btnRequest.setEnabled(false);
            }
        }
    }//GEN-LAST:event_interviewTableMouseClicked
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBack;
    private javax.swing.JButton btnChangePass;
    private javax.swing.JButton btnChangePassCancel;
    private javax.swing.JButton btnChangePassSave;
    private javax.swing.JButton btnRequest;
    private javax.swing.JButton btnResult;
    private javax.swing.JTable interviewTable;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JPasswordField jPasswordField2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblError;
    private javax.swing.JLabel lblErrorSalary;
    private javax.swing.JLabel lblName;
    private javax.swing.JTextField txtSalary;
    // End of variables declaration//GEN-END:variables

    @Override
    public void startFrame(JFrame app) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(InterviewerGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        this.root = app;
        root.setVisible(false);
        this.setVisible(true);
    }

    @Override
    public void exitFrame() {
        root.setVisible(true);
        this.setVisible(false);
    }
    private JFrame root;
}
